import React from 'react';
import PropTypes from 'prop-types';
import { CompositeDecorator } from 'draft-js';
import Link from 'widget/Link';

function findLinkEntities(contentBlock, callback, contentState) {
  contentBlock.findEntityRanges(character => {
    const entityKey = character.getEntity();
    return entityKey !== null && contentState.getEntity(entityKey).getType() === 'LINK';
  }, callback);
}

const RichLink = props => {
  const { url } = props.contentState.getEntity(props.entityKey).getData();
  return (
    <Link title={url} href={url}>
      {props.children}
    </Link>
  );
};

const decorator = new CompositeDecorator([
  {
    strategy: findLinkEntities,
    component: RichLink
  }
]);

RichLink.propTypes = {
  // eslint-disable-next-line react/forbid-prop-types
  contentState: PropTypes.any.isRequired,
  // eslint-disable-next-line react/forbid-prop-types
  entityKey: PropTypes.any.isRequired,
  children: PropTypes.node.isRequired
};

export default decorator;
